//
//  MusicDownloadTask.m
//  DownloadDemo
//
//  Created by 陈凯 on 16/4/27.
//  Copyright © 2016年 鸥！陈凯. All rights reserved.
//

#import "MusicDownloadTask.h"

@interface MusicDownloadTask ()<NSURLSessionDownloadDelegate>

@property (nonatomic, copy) ProgressBlock progressBlock;
@property (nonatomic, copy) CompleteBlock completeBlock;

@property (nonatomic, strong) NSString *mp3Name;
@property (nonatomic,strong) NSURLSessionDownloadTask *dTask;
@end

@implementation MusicDownloadTask
- (void)downloadUrl:(NSURL *)url progressBlock:(ProgressBlock)proBlock complete:(CompleteBlock)comBlock {
    self.progressBlock = proBlock;
    self.completeBlock = comBlock;
    self.mp3Name       = [url.absoluteString stringByReplacingOccurrencesOfString:@"/" withString:@"_"];
    self.mp3Name       = [self.mp3Name stringByReplacingOccurrencesOfString:@":" withString:@"_"];
    
    // 网络请求
    NSURLSession *session = [NSURLSession sessionWithConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration] delegate:self delegateQueue:[NSOperationQueue mainQueue]];
    //
    self.dTask = [session downloadTaskWithURL:url];
    // 启动任务
    [self.dTask resume];
}

// 下载
- (void)URLSession:(NSURLSession *)session downloadTask:(NSURLSessionDownloadTask *)downloadTask didWriteData:(int64_t)bytesWritten totalBytesWritten:(int64_t)totalBytesWritten totalBytesExpectedToWrite:(int64_t)totalBytesExpectedToWrite {
    // 下载进度
    float progress = totalBytesWritten * 1.0 / totalBytesExpectedToWrite;
    // 回调block
    if (self.progressBlock) {
        self.progressBlock(progress);
    }
}

// 下载完成
- (void)URLSession:(NSURLSession *)session downloadTask:(NSURLSessionDownloadTask *)downloadTask didFinishDownloadingToURL:(NSURL *)location {
    NSLog(@"%@",[location path]);
    // 得到Caches文件目录
    NSString *cachesPath = NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES)[0];
    NSString *filePath = [cachesPath stringByAppendingPathComponent:self.mp3Name];
    // 移动到caches文件夹
    [[NSFileManager defaultManager]moveItemAtPath:[location path] toPath:filePath error:nil];
    
    NSLog(@"%@",filePath);
    if (self.completeBlock) {
        self.completeBlock(filePath);
    }
}

//开始
- (void)resume {
    [self.dTask resume];
}
//暂停
- (void)suspend {
    [self.dTask suspend];
}

//修改block
- (void)setProgressBlock:(ProgressBlock)proBlock {
    if (_progressBlock != proBlock) {
        _progressBlock = proBlock;
    }
}
- (void)setCompleteBlock:(CompleteBlock)comBlock {
    if (_completeBlock != comBlock) {
        _completeBlock = comBlock;
    }
}




@end
